import { useEffect, useState } from 'react'
import debounce from 'lodash.debounce'
import { noteService } from '../service/noteService.ts'
import {
  NoteSearchQueryParams,
  NoteWithRelations,
} from '@/domain/note/types/serviceTypes.ts'
import { Pagination } from '@/request'

/**
 * 根据关键字搜索问题，添加 debounce 处理
 *
 * @param noteSearchQueryParams 搜索参数
 */
export function useSearchNote(noteSearchQueryParams: NoteSearchQueryParams) {
  /**
   * 笔记列表
   */
  const [noteList, setNoteList] = useState<NoteWithRelations[]>([])
  const [loading, setLoading] = useState(false)

  /**
   * 分页参数
   */
  const [pagination, setPagination] = useState<Pagination>()

  useEffect(() => {
    // 处理关键字为空的情况
    if (
      noteSearchQueryParams.keyword === undefined ||
      noteSearchQueryParams.keyword.trim() === ''
    ) {
      setNoteList([])
      return
    }

    const searchNote = debounce(async () => {
      setLoading(true)
      const { data, pagination } = await noteService.searchNoteService(
        noteSearchQueryParams,
      )

      setNoteList(data)
      setPagination(pagination)
      setLoading(false)
    }, 300) // 延迟 300 ms

    searchNote()
  }, [noteSearchQueryParams])

  return {
    loading,
    noteList,
    pagination,
  }
}
